﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Data;
using Gift.WebApp;
using Gift.Model;
using Gift.DAL;

namespace WebSite.admin.order
{
    public partial class orders : BaseAdmin
    {
     
        // Fields
        public string cardprice = "0";
        public StringBuilder sbCarmsg = new StringBuilder();

        public string payprice = "0";

        public string scoreprice = "0";
        public string sumprice = "0";

        public string totalprice = "0";

        public string SendCompany = string.Empty;
        public string SendCode = string.Empty;
        public string SendUrl = string.Empty;
        public string SendTelphone = string.Empty;
        public string SendDate1 = string.Empty;
        public string SendPerson = string.Empty;
        public string SendPersonCompany = string.Empty;
        public string SendPersonAddress = string.Empty;

        // Methods
        private void Bind()
        {
            string sql = "select orderid, memberid, (select userName from tbUser where id=tbCardOrder.memberid) as memberlogin, pay, ship, cname, tel, phone, post, address, email, [content], cname1, tel1, phone1, post1, address1, email1, content1, states, "
                     + " ordertime, paytime, shiptime, languages, totalprice, cardprice, scoreprice, orderscore, cardid, scoretype, SendCompany, SendCode, convert(varchar(10),senddate,111) as senddate, isnull(SendDate1,'') as TempSendDate1, "
                     + " SendUrl,SendTelphone,SendPerson,SendPersonCompany,SendPersonAddress "
                    + "  from tbCardOrder where orderid=" + base.Request.QueryString["oid"].ToString() + "";
            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            if (table.Rows.Count > 0)
            {
                this.ordercode.Text = table.Rows[0]["orderId"].ToString();

                //if (!string.IsNullOrEmpty(table.Rows[0]["memberid"].ToString()) && table.Rows[0]["memberid"].ToString() != "0")
                //{
                //    this.lblCardCode.Text = "会员名(" + table.Rows[0]["memberlogin"] + ")通过卡内余额支付";
                //}
                //else
                //{
                    DataTable dtCards = new DataTable();
                    dtCards = SQLAccess.GreatDs("select o.cardId,oa.companyCode from tbCardOrder o join tbOrderAccount oa "
                                                + " on o.OrderId = oa.OrderId "
                                                 + " where o.orderId=" + this.ordercode.Text + "").Tables[0];
                    int iRow = 0;
                    foreach (DataRow drCard in dtCards.Rows)
                    {
                        DALCard theCard = new DALCard(drCard["companyCode"].ToString());
                        tbCard oCard = theCard.GetModel(int.Parse(drCard["cardId"].ToString()));
                        if(oCard != null)
                        {
                            iRow++;
                            if (iRow % 5 == 0)
                            {
                                this.lblCardCode.Text += oCard.cardcode + "|\n";
                            }
                            else
                            {
                                this.lblCardCode.Text += oCard.cardcode + "|";
                            }
                        }
                    }
              //  }

                    this.SendCompany = table.Rows[0]["SendCompany"].ToString();
                    this.SendCode = table.Rows[0]["SendCode"].ToString();
                    this.SendUrl = table.Rows[0]["SendUrl"].ToString();
                    this.SendTelphone = table.Rows[0]["SendTelphone"].ToString();
                    this.SendDate1 = table.Rows[0]["TempSendDate1"].ToString() == "" ? string.Empty : DateTime.Parse(table.Rows[0]["TempSendDate1"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                    if (SendDate1.Contains("1900-01-01")) SendDate1 = string.Empty;
                    this.SendPerson = table.Rows[0]["SendPerson"].ToString();
                    this.SendPersonCompany = table.Rows[0]["SendPersonCompany"].ToString();
                    this.SendPersonAddress = table.Rows[0]["SendPersonAddress"].ToString();


                this.memberid.Text = table.Rows[0]["cname"].ToString();
                this.states1.Value = table.Rows[0]["states"].ToString();
                this.contents.Text = table.Rows[0]["content1"].ToString();
                string str2 = "select * from tbPay where pay in (" + table.Rows[0]["pay"].ToString() + ")";
                DataTable table2 = new DataTable();
                table2 = SQLAccess.GreatDs(str2).Tables[0];

                this.pay.Text = "";
                foreach (DataRow dr in table2.Rows)
                {
                    this.pay.Text = this.pay.Text != "" ? this.pay.Text + ";" + dr["payname"].ToString() : dr["payname"].ToString();
                }

                this.payprice = "0";
                if (table.Rows[0]["scoreprice"].ToString() != "0")
                {
                   // this.paytime.Text = "积分支付：" + table.Rows[0]["scoreprice"].ToString();
                    this.scoreprice = table.Rows[0]["scoreprice"].ToString();
                }
                else
                {
                   // this.paytime.Text = "未使用积分";
                }
                if ((table.Rows[0]["cardid"].ToString() != "0") && (table.Rows[0]["cardprice"].ToString() != "0"))
                {
                    DataTable table3 = SQLAccess.GreatDs("select cardcode from tbCard where cardid=" + table.Rows[0]["cardid"].ToString() + "").Tables[0];
                    if (table3.Rows.Count > 0)
                    {
                       // this.shiptime.Text = "礼品卡卡号：" + table3.Rows[0]["cardcode"].ToString() + " 支付金额：" + table.Rows[0]["cardprice"].ToString();
                        this.cardprice = table.Rows[0]["cardprice"].ToString();
                    }
                    else
                    {
                        //this.shiptime.Text = "";
                    }
                }
    
                this.orderno.Text = table.Rows[0]["content"].ToString();
                if (table.Rows[0]["states"].ToString() == "0")
                {
                    this.states.Text = "新订单";
                    if (base.Request.QueryString["flag"] == "1")
                    {
                        this.txtAddress.ReadOnly = false;
                        this.txtCname.ReadOnly = false;

                        this.txtPhone.ReadOnly = false;
                        this.txtSendTime.ReadOnly = false;
                        this.txtTel.ReadOnly = false;
                        this.btnUpdateAddress.Enabled = true;
                    }
                    else
                    {
                        this.txtAddress.ReadOnly = true;
                        this.txtCname.ReadOnly = true;

                        this.txtPhone.ReadOnly = true;
                        this.txtSendTime.ReadOnly = true;
                        this.txtTel.ReadOnly = true;
                        this.btnUpdateAddress.Enabled = false;
                    }
                }
                else
                {
                    this.txtAddress.ReadOnly = true;
                    this.txtCname.ReadOnly = true;

                    this.txtPhone.ReadOnly = true;
                    this.txtSendTime.ReadOnly = true;
                    this.txtTel.ReadOnly = true;
                    this.btnUpdateAddress.Enabled = false;
                }
                if (table.Rows[0]["states"].ToString() == "0")
                {
                    this.states.Text = "新订单";
                }
                else if (table.Rows[0]["states"].ToString() == "1")
                {
                    this.states.Text = "备货中";
                }
                else if (table.Rows[0]["states"].ToString() == "2")
                {
                    this.states.Text = "已发货";
                }
                else if (table.Rows[0]["states"].ToString() == "3")
                {
                    this.states.Text = "已完成";
                }
                else if (table.Rows[0]["states"].ToString() == "5")
                {
                    this.states.Text = "已取消";
                }
                this.ordertime.Text = table.Rows[0]["ordertime"].ToString();
                this.txtCname.Text = table.Rows[0]["cname1"].ToString();
                this.txtAddress.Text = table.Rows[0]["address1"].ToString();
                this.txtTel.Text = table.Rows[0]["tel1"].ToString();
                this.txtSendTime.Text = table.Rows[0]["sendDate"].ToString();
                this.txtPhone.Text = table.Rows[0]["phone1"].ToString();
                this.cardprice = table.Rows[0]["cardprice"].ToString();
                DataTable table5 = SQLAccess.GreatDs("select sum(tbCar.prodNumber) as pronum,tbCar.OrderId, tbCar.prodprice,sum(tbCar.prodprice * tbCar .prodNumber ) as sumprice,tbCar.contents,g.goodsname,ge.saleprice,g.id,(select top 1 thumbImg from tbGoodGallery where goods = g.id) as thumbImg   "
                         + " from tbCar inner join tbGoods g on tbCar.productid=g.id join tbGoodsEntitys ge on ge.goods = g.Id "
                         + " where tbCar.orderid=" + table.Rows[0]["orderid"].ToString()
                         + " group by tbCar.OrderId, tbCar.prodNumber,tbCar.prodprice,tbCar.contents,g.goodsname,ge.saleprice,g.id ").Tables[0];
                if (table5.Rows.Count > 0)
                {
                    foreach (DataRow row in table5.Rows)
                    {
                        this.sumprice = string.Format("{0:f}", Convert.ToSingle(this.sumprice) + Convert.ToSingle(row["sumprice"]));
                        this.sbCarmsg.Append("<tr bgcolor='#ffffff'>");
                        this.sbCarmsg.Append( "<td width='25%' align='center'><a href='/cn/products_details.aspx?pid=" + row["id"].ToString() + "' target=_blank><img src='" + row["thumbImg"].ToString() + "' border=0 alt=''/></a></td> ");
                        this.sbCarmsg.Append( "<td><font style='FONT-WEIGHT: bold' color='#339900'>" + row["goodsName"].ToString() + "</font>&nbsp;<br/>" + row["contents"].ToString() + "</td>");
                        this.sbCarmsg.Append("<td width='20%' align='middle'>" + string.Format("{0:f}", row["prodprice"]) + " 元</td>");
                        this.sbCarmsg.Append("<td width='10%' align='middle'>" + row["pronum"].ToString() + "</td>");
                        this.sbCarmsg.Append( "<td width='15%' align='middle'>" + string.Format("{0:f}", row["sumprice"]) + "元</td>");
                         string sOperate = string.Empty;
                         if (BaseFactory.theWarehouseGoodsOut.IsOutWarehouse(long.Parse(row["orderId"].ToString()), int.Parse(row["id"].ToString()), int.Parse(row["pronum"].ToString())))
                        {
                            sOperate = string.Format("<a onclick=\"openModalForm('/admin/warehouse/cardGoodsOut.aspx?gid={0}&gcount={1}&oid={2}');\" style=\"cursor:point;\" >出库</a>"
                                                             , row["id"].ToString()
                                                             , row["pronum"].ToString()
                                                             , row["orderid"].ToString());
                        }

                        this.sbCarmsg.AppendFormat("<td width='15%' align='middle'>{0}</td>", sOperate);
                        this.sbCarmsg.Append( "</tr>");
                    }
                }
                this.totalprice = string.Format("{0:f}", (((Convert.ToSingle(this.sumprice) + Convert.ToSingle(this.payprice))) - Convert.ToSingle(this.cardprice)) - Convert.ToSingle(this.scoreprice));
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //if ((this.states1.Value.ToString() == "1") || (this.states1.Value.ToString() == "2"))
            //{
            //    DataTable table = SQLAccess.GreatDs("select memberid,ordercode,orderscore,scoreprice,scoretype from tbCardOrder where orderid=" + base.Request.QueryString["oid"] + "").Tables[0];
            //    if ((table.Rows.Count > 0) && (table.Rows[0]["scoretype"].ToString() == "0"))
            //    {
            //        SQLAccess.DoSql(string.Concat(new object[] { "Update DB_Member set score1=score1+", Convert.ToInt32(table.Rows[0]["orderscore"]) - Convert.ToInt32(table.Rows[0]["scoreprice"]), ",score2=score2-", Convert.ToInt32(table.Rows[0]["scoreprice"]), ",score3=score3+", Convert.ToInt32(table.Rows[0]["orderscore"]), " where memberid=", table.Rows[0][0].ToString(), "" }));
            //        SQLAccess.DoSql(string.Concat(new object[] { "insert into DB_Score (memberid,scorename,scoreprice,content,updatetime,scoretype) values (", table.Rows[0][0].ToString(), ",'订单赠积分：", table.Rows[0]["ordercode"], "','+", table.Rows[0]["orderscore"], "','赠积分：", table.Rows[0]["orderscore"], "','", DateTime.Now, "',0)" }));
            //    }
            //}
            SQLAccess.DoSql("update tbCardOrder set states=" + this.states1.Value + ",content1='" + re.replace(this.contents.Text) + "',scoretype=1 where orderid=" + base.Request.QueryString["oid"] + "");
            base.Alert("alert('操作成功！');window.location.href='orderCardList.aspx';");
            base.Response.End();
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            string sql = "select * from tbCardOrder where orderid<" + base.Request.QueryString["oid"] + " order by orderid desc";
            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            if (table.Rows.Count > 0)
            {
                base.Response.Redirect("orders.aspx?oid=" + table.Rows[0]["orderid"].ToString() + "");
                base.Response.End();
            }
            else
            {
                base.Response.Redirect("orders.aspx?oid=" + base.Request.QueryString["oid"] + "");
                base.Response.End();
            }
        }

        protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
        {
            string sql = "select * from tbCardOrder where orderid>" + base.Request.QueryString["oid"] + " order by orderid asc";
            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            if (table.Rows.Count > 0)
            {
                base.Response.Redirect("orders.aspx?oid=" + table.Rows[0]["orderid"].ToString() + "");
                base.Response.End();
            }
            else
            {
                base.Response.Redirect("orders.aspx?oid=" + base.Request.QueryString["oid"] + "");
                base.Response.End();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {


            if (!base.IsPostBack && (base.Request.QueryString["oid"] != ""))
            {
                this.Bind();
                this.BindCompainTypeList();
                this.BindCompain();
                if (base.Request.QueryString["flag"] == "1")
                {
                    this.tbOperate.Visible = true;
                    this.tblCompain.Visible = false;
                }
                else if (base.Request.QueryString["flag"] == "2")
                {
                    this.tbOperate.Visible = false;
                    this.tblCompain.Visible = true;
                }
                else
                {
                    this.tbOperate.Visible = false;
                    this.tblCompain.Visible = false;
                }
            }
        }

        void BindCompainTypeList()
        {
            DataSet ds;
            ds = BaseFactory.theCompain.GetList("");
            if (ds != null && ds.Tables.Count > 0)
            {
                this.ddlCompainType.DataTextField = "CompainName";
                this.ddlCompainType.DataValueField = "CompainId";
                this.ddlCompainType.DataSource = ds.Tables[0].DefaultView;
                this.ddlCompainType.DataBind();
                this.ddlCompainType.Items.Insert(0, new ListItem("投诉类别...", "0"));
            }

            tbCardOrder oOrder;
            oOrder = BaseFactory.theCardOrder.GetModel(Int64.Parse(base.Request.QueryString["oid"]));
            tbOrderCompain oOrderCompain;
            oOrderCompain = BaseFactory.theOrderCompain.GetModelByOrderId(oOrder.orderid);
            if (oOrderCompain != null)
            {
                this.ddlCompainType.Items.FindByValue(oOrderCompain.CompainId.ToString()).Selected = true;
                this.txtCompain.Text = oOrderCompain.Content;
            }
        }

        protected void btnCompain_Click(object sender, EventArgs e)
        {
            if (this.txtCompain.Text.Trim() == "")
            {
                base.Alert("投诉内容不能为空！");
                return;
            }
              tbCardOrder oOrder;
              oOrder = BaseFactory.theCardOrder.GetModel(int.Parse(base.Request.QueryString["oid"]));
            tbOrderCompain oOrderCompain;
            oOrderCompain = BaseFactory.theOrderCompain.GetModelByOrderId(oOrder.orderid);
           
            if (oOrderCompain == null)
            {
                oOrderCompain = new tbOrderCompain();
                oOrderCompain.CompainId = int.Parse(this.ddlCompainType.SelectedItem.Value);
                oOrderCompain.Content = this.txtCompain.Text.Trim();
                oOrderCompain.OrderId = oOrder.orderid;
                oOrderCompain.AddDate = DateTime.Now;
                BaseFactory.theOrderCompain.Add(oOrderCompain);
            }
            else
            {
                oOrderCompain.CompainId = int.Parse(this.ddlCompainType.SelectedItem.Value);
                oOrderCompain.Content = this.txtCompain.Text.Trim();
                oOrderCompain.OrderId = oOrder.orderid;
                oOrderCompain.AddDate = DateTime.Now;
                BaseFactory.theOrderCompain.Update(oOrderCompain);
            }

        }

        private void BindCompain()
        {
            tbCardOrder oOrder;
            oOrder = BaseFactory.theCardOrder.GetModel(Int64.Parse(base.Request.QueryString["oid"]));
            tbOrderCompain oOrderCompain;
            oOrderCompain = BaseFactory.theOrderCompain.GetModelByOrderId(oOrder.orderid);
            if (oOrderCompain != null)
            {
                this.ddlCompainType.Items.FindByValue(oOrderCompain.CompainId.ToString()).Selected = true;
                this.txtCompain.Text = oOrderCompain.Content;
                this.txtProcess.Text = oOrderCompain.Process;
            }
        }

        protected void btnProcess_Click(object sender, EventArgs e)
        {
            tbCardOrder oOrder;
            oOrder = BaseFactory.theCardOrder.GetModel(int.Parse(base.Request.QueryString["oid"]));
            tbOrderCompain oOrderCompain;
            oOrderCompain = BaseFactory.theOrderCompain.GetModelByOrderId(oOrder.orderid);
            if (this.txtProcess.Text.Trim() == "")
            {
                base.Alert("处理结果不能为空！");
                return;
            }

            if (oOrderCompain == null)
            {
                oOrderCompain = new tbOrderCompain();
                oOrderCompain.CompainId = int.Parse(this.ddlCompainType.SelectedItem.Value);
                oOrderCompain.Content = this.txtCompain.Text.Trim();
                oOrderCompain.OrderId = oOrder.orderid;
                oOrderCompain.Process = this.txtProcess.Text.Trim();
                oOrderCompain.ProcessDate = DateTime.Now;
                BaseFactory.theOrderCompain.Add(oOrderCompain);
            }
            else
            {
                oOrderCompain.CompainId = int.Parse(this.ddlCompainType.SelectedItem.Value);
                oOrderCompain.Content = this.txtCompain.Text.Trim();
                oOrderCompain.OrderId = oOrder.orderid;
                oOrderCompain.Process = this.txtProcess.Text.Trim();
                oOrderCompain.ProcessDate = DateTime.Now;
                BaseFactory.theOrderCompain.Update(oOrderCompain);
            }
            base.Alert("保存成功！");
            return;
        }

        protected void btnUpdateAddress_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime.Parse(this.txtSendTime.Text);
            }
            catch
            {
                base.Alert("送货日期格式不正确！");
                return; 
            }
            string strSql = "update tbCardOrder set address1='" + this.txtAddress.Text.Trim() +"'"
                           + ", cname1='" + this.txtCname.Text.Trim() +"'"
                           + ", sendDate='" + this.txtSendTime.Text.Trim() + "'"
                           + ", tel1='" + this.txtTel.Text.Trim() + "'"
                           + ", phone1='" + this.txtPhone.Text.Trim() + "'"                  
                           + " where orderid=" + base.Request.QueryString["oid"].ToString() + "";
            SQLAccess.DoSql(strSql);
            base.Alert("更新成功！");
            return;
        }

    }
}